/*!
 * mainframe.js	v0.1
 * Author: sunsh
 * Date: 2017.9.28
 * Copyright 2017 AVIT
 */
var	refreshTimer;
var networkTimeout;
var	xmlHttpNetwork;
var	xmlHttpSRTset;
var	xmlHttpIPRecvset;
var	xmlHttpVersion;
var	xmlHttpInputSource;

var	currentInputSource;
var currentIPRecvMode;
var currentUnicastIP;
var	currentMulticastIP;
var	currentIPRecvPort;

var RouteTableJSON;
var NewRouteTableJSON;

var	currentSRTEnable;
var	currentSRTMode;
var	currentSRTCallerAddr;
var	currentSRTPort;
  
var	currentSRTToL;
var	currentSRTToS;
var	currentSRTMTU;

//status
var xmlHttpStatus;
var xmlintelHttpStatus;
var currentTotalBitrate;
var currentProgramNo;
var currentInputSource;
var currentStreamType;
var currentDecodingState;
var currentFanState;
var currentTemp;
var currentAudioCodec;
var currentAudio1BitRate;
var currentAudio2BitRate;
var currentVideoFormat;
var currentVideoBitrate;
var currentProfile;
var currentChrome;
var currentLevel;
var currentDelayMode;
var currentPMTPID;
var currentPCRPID;
var currentVideoPID;
var currentAudio1PID;
var currentAudio2PID;
var currentSampleDepth;
var currentStreamHdr;
var currentSrtStatus;
var xmlHttpAlarmInfo;
var xmlHttpClearAlarmInfo;
var currentAlarmInfoLen;
var currentAlarmInfoStr;
var ArrayAlarmInfoStr = new Array();
var ArrayAlarmInfoLen = new Array();
var refreshAlarm;
//configure
var xmlHttpConfigure;
var xmlHttpHideConfig;
var xmlHttpNTTConfigure;
var currentInputSource;
var currentIP_receive_mode;
var currentUDPTargetPort;
var currentNetworkdelay;
var currentSRTMode;
var currentSRTEncryption;
var currentSRTPassphrase;
var currentSRTCallerAddr;

var currentSRTToL;
var currentSRTToS;
var currentSRTMTU;
var currentSRTBandOver;
var currentSRTLatency;
var currentProgramList;
var currentProgramCount;
var currentAnaVolume;
var currentErrorPicture;
var currentTimeout;
var currentOutputFormat;
var currentResumeTime;
var currentHdrMode;
var currentLatencyMode;
var currentSampleFormat;
var currentSDIMode;
var currentGenlock;
var currentRateMode;

//ASI para
var currentAsiPcrPid;
var currentAsiVideoPid;
var currentAsiAudioPid;

var ArrayProgram = new Array();
//network
var ArrayRouteList = new Array();
var currentDeaultInterface;
var currentRouteList;
//system
var xmlHttpSystem;
var currentSRTLic;
var currentBasicLic;
var currentFirmverion;
var currentFPGAverion;
var currentM50version;
var currentSerialNo;
var refreshStreamTimer;
var input_sour_cnt = 1;

var xmlHttpWifi;
//other
var xmlHttpTalkData;
var xmlHttpTalk;
var xmlHttpTalkStatus;
var refreshWait;
var refreshWaitFlag = 0;
var WaitCount = 0;

function RefreshStatusSettings() {
	//getTemprature();
    //Decoder Status
    if (window.XMLHttpRequest) {// code for all new browsers
        xmlHttpStatus = new XMLHttpRequest();
    }
    else if (window.ActiveXObject) {
        xmlHttpStatus = new ActiveXObject("Microsoft.XMLHTTP");
    }
    if (xmlHttpStatus == null) {
        return;
    }
    var url = "/cgi-bin/getStatus.cgi";
    xmlHttpStatus.onreadystatechange = stateChangedStatus;
    xmlHttpStatus.open("GET", url, true);
    xmlHttpStatus.setRequestHeader("If-Modified-Since", "0")
    xmlHttpStatus.setRequestHeader("Cache-Control", "no-cache");
    xmlHttpStatus.send(null);
    //cgi_get_streaminfo("HDD461-SRC", update_streaminfo, convert_instream_status);
}

function RefreshConfigureSettings() {
    //configure	setting
    getConfigure();
}

function RefreshNetworkSettings() {
    getNetwork();
}

function RefreshSystemSettings() {

    if (window.XMLHttpRequest) {// code	for	all	new	browsers
        xmlHttpSystem = new XMLHttpRequest();
    }
    else if (window.ActiveXObject) {// code	for	IE5	and	IE6
        xmlHttpSystem = new ActiveXObject("Microsoft.XMLHTTP");
    }
    if (xmlHttpSystem == null) {
        return;
    }

    var url = "/cgi-bin/getSystem.cgi";
    xmlHttpSystem.onreadystatechange = stateChangedSystem;
    xmlHttpSystem.open("GET", url, true);
    xmlHttpSystem.setRequestHeader("If-Modified-Since", "0")
    xmlHttpSystem.setRequestHeader("Cache-Control", "no-cache");
    xmlHttpSystem.send(null);
}

//state get status
function stateChangedStatus() {
    if (xmlHttpStatus.readyState == 4 || xmlHttpStatus.readyState == "complete") {
        if (xmlHttpStatus.status == 200) {
            xmlDoc = xmlHttpStatus.responseXML;
            xmlNode = xmlDoc.getElementsByTagName("StatusDetails")[0];
            //1 decode
            currentTotalBitrate = xmlNode.getElementsByTagName("StatusTotalBitrate")[0].textContent;
            currentInputSource = xmlNode.getElementsByTagName("StatusInputSource")[0].textContent;
            currentDecodingState = xmlNode.getElementsByTagName("DecodingState")[0].textContent;
            currentTemp = xmlNode.getElementsByTagName("Temperature")[0].textContent;
            //audio
            currentAudioCodec = xmlNode.getElementsByTagName("StatusAudioCodec")[0].textContent;
            currentAudio1BitRate = xmlNode.getElementsByTagName("Audio1Rate")[0].textContent;
			//video
            currentVideoFormat = xmlNode.getElementsByTagName("VideoFormat")[0].textContent;
            currentChrome = xmlNode.getElementsByTagName("Chrome")[0].textContent;
			currentRateMode = xmlNode.getElementsByTagName("RateMode")[0].textContent;
            //pid
            currentPMTPID = xmlNode.getElementsByTagName("PMTPID")[0].textContent;
            currentPCRPID = xmlNode.getElementsByTagName("PCRPID")[0].textContent;
            currentVideoPID = xmlNode.getElementsByTagName("VideoPID")[0].textContent;
            currentAudio1PID = xmlNode.getElementsByTagName("Audio1PID")[0].textContent;
        } else {
            //decode
            currentTotalBitrate = 0;
            currentInputSource = "IP";
            currentDecodingState = "Stop";
            currentFanState = 0;
            currentTemp = 30;
            //audio
            currentAudioCodec = "MPEG1_L2";
            currentAudio1BitRate = 0;
            //video
            currentVideoFormat = "1080I50";
            currentChrome = "4:2:0";
            //pid
            currentPMTPID = "0x0033";
            currentPCRPID = "0x0081";
            currentVideoPID = "0x0002";
            currentAudio1PID = "0x0512";
			currentRateMode = "Unknown";
        }

        // decode
        if (currentTotalBitrate > 0)
        {
            document.getElementById("Date_BTN").disabled = true;
            document.getElementById("apply_date_time_BTN_id").disabled = true;
        }
        else
        {
            document.getElementById("Date_BTN").disabled = false;
            document.getElementById("apply_date_time_BTN_id").disabled = false;
        }
        document.getElementById("StatusTotalBitrate").innerHTML = currentTotalBitrate + "kbps";
        document.getElementById("StatusInputSource").innerHTML = currentInputSource;

		if (currentTotalBitrate < 128 || currentDecodingState == "Stopped") {  // Stopped
            document.getElementById("EncStatusMis").style.display = "none";
            document.getElementById("EncStatusStop").style.display = "inline";
            document.getElementById("EncStatusRunning").style.display = "none";
		}
        else if (currentDecodingState == "Mismatch" && currentTotalBitrate > 128) { // Mismatch
            document.getElementById("EncStatusMis").style.display = "inline";
            document.getElementById("EncStatusStop").style.display = "none";
            document.getElementById("EncStatusRunning").style.display = "none";
        } else 
		{    // Running
            document.getElementById("EncStatusMis").style.display = "none";
            document.getElementById("EncStatusStop").style.display = "none";
            document.getElementById("EncStatusRunning").style.display = "inline";
        }
        document.getElementById("TempFValue").innerHTML = parseInt(currentTemp * 1.8 + 32);
        document.getElementById("TempCValue").innerHTML = currentTemp;
        ChangeInputSourceStatus(currentInputSource);
        //audio
        document.getElementById("StatusAudioCodec").innerHTML = currentAudioCodec;
        if (currentAudioCodec == "LPCM") {
            hide_item_by_id("audiorate_div");
        }
        else {
            show_item_by_id("audiorate_div");
        }
        document.getElementById("StatusAudio1Bitrate").innerHTML = currentAudio1BitRate + "kbps";
        //video
        document.getElementById("StatusVideoFormat").innerHTML = currentVideoFormat;
        document.getElementById("StatusChrome").innerHTML = currentChrome;
        document.getElementById("StatusRateMode").innerHTML = currentRateMode;
        //pid
        document.getElementById("StatusPMTPID").innerHTML = currentPMTPID;
        document.getElementById("StatusPCRPID").innerHTML = currentPCRPID;
        document.getElementById("StatusVideoPID").innerHTML = currentVideoPID;
        document.getElementById("StatusAudio1PID").innerHTML = currentAudio1PID;
    }
}

//state get system
function stateChangedSystem()
{
    if (xmlHttpSystem.readyState == 4 || xmlHttpSystem.readyState == "complete") {
        if (xmlHttpSystem.status == 200) {
            xmlDoc = xmlHttpSystem.responseXML;
            xmlNode = xmlDoc.getElementsByTagName("SystemDetails")[0];

            currentFirmverion = xmlNode.getElementsByTagName("FirmwareVersion")[0].textContent;
            currentFPGAverion = xmlNode.getElementsByTagName("FPGAVersion")[0].textContent;
            currentSerialNo = xmlNode.getElementsByTagName("SerialNo")[0].textContent;

            currentWifiSwitch = xmlNode.getElementsByTagName("WifiSwitch")[0].textContent;
            currentWifiName = xmlNode.getElementsByTagName("WifiName")[0].textContent;
            currentWifiPasswd = xmlNode.getElementsByTagName("WifiPasswd")[0].textContent;
        }
        else {
            currentFirmverion = "1.0.0";
            currentFPGAverion = "180101";
            currentSerialNo = "12345678H02";

            currentWifiSwitch = 0;
            currentWifiName = "wifi";
            currentWifiPasswd = "test";
        }

        // Version
        document.getElementById("Version").value = currentFirmverion;
        document.getElementById("FpgaVersion").value = currentFPGAverion;
        // Serial Number
        document.getElementById("Serial").value = currentSerialNo;
        //Wlan
        $("#Wlan_Switch").val(currentWifiSwitch);
        document.getElementById("wlan_name").value = currentWifiName;
        document.getElementById("wlan_passwd").value = currentWifiPasswd;
    }
}

//Wlan
$('#Wifi_Apply_BTN').click(function () {
    show_item_by_id("Apply_Wifi_BTN_Group");
});

$('#Apply_Wifi_Confirm_BTN').click(function () {
    hide_item_by_id("Apply_Wifi_BTN_Group");
    wlan_save();
});

$('#Apply_Wifi_Cancel_BTN').click(function () {
    close_reveal_modal_by_id("Apply_WifiModal");
});

function wlan_save() {
    if (window.XMLHttpRequest) {// code for all new browsers
        xmlHttpWifi = new XMLHttpRequest();
    }
    else if (window.ActiveXObject) {
        xmlHttpWifi = new ActiveXObject("Microsoft.XMLHTTP");
    }
    if (xmlHttpWifi == null) {
        return;
    }

    var url = "/cgi-bin/ApplyWifi.cgi?";
    url = url + "WifiSwitch=" + document.getElementById("Wlan_Switch").value;
    url = url + "&Wifiname=" + document.getElementById("wlan_name").value;
    url = url + "&Wifipasswd=" + document.getElementById("wlan_passwd").value;

    xmlHttpWifi.onreadystatechange = stateApplyWifi;
    xmlHttpWifi.open("GET", url, true);
    xmlHttpWifi.setRequestHeader("If-Modified-Since", "0")
    xmlHttpWifi.setRequestHeader("Cache-Control", "no-cache");
    xmlHttpWifi.send(null);
}

function stateApplyWifi() {
    if (xmlHttpWifi.readyState == 4 || xmlHttpWifi.readyState == "complete") {
        if (xmlHttpWifi.status == 200) {
            if (xmlHttpWifi.responseText == "OK") {
                show_reveal_str("wifi_set_label", "Set wifi parameters successfully!", "#24d401");
                setTimeout('close_reveal_modal_by_id("Apply_WifiModal")', 1000);
            }
            else {
                show_reveal_str("wifi_set_label", "Failed to set wifi parameters, please check!", "#ff0000");
            }
        }
    }
}

function ChangeInputSourceStatus(str) {
	t = Number(str);
    switch (t) {
        case 2:	//RTSP
           
            hide_item_by_id("SRTStatus_Group");
            show_item_by_id("StreamType_Group");
            break;
        case 1:	//SRT
            
            show_item_by_id("SRTStatus_Group");
            show_item_by_id("StreamType_Group");
            break;
        case 0:	//IP
           
            hide_item_by_id("SRTStatus_Group");
            show_item_by_id("StreamType_Group");
            break;
        default:
            break;
    }
}

function StartMonitor() {

}

//warning&close
function AddWarningInfo(str) {
    var strContent = document.getElementById("warninginfo").value;

    strContent = strContent + str + "\n";
    document.getElementById("warninginfo").innerHTML = strContent;
}

function RefreshAlarmInfoSettings() {
    //clear txt
    //document.getElementById("warninginfo").innerHTML = "";

    if (window.XMLHttpRequest) {// code for all new browsers
        xmlHttpAlarmInfo = new XMLHttpRequest();
    }
    else if (window.ActiveXObject) {// code for IE5 and IE6
        xmlHttpAlarmInfo = new ActiveXObject("Microsoft.XMLHTTP");
    }
    if (xmlHttpAlarmInfo == null) {
        return;
    }
    var url = "/cgi-bin/getAlarmInfo.cgi";
    xmlHttpAlarmInfo.onreadystatechange = stateChangedAlarmInfo;
    xmlHttpAlarmInfo.open("GET", url, true);
    xmlHttpAlarmInfo.setRequestHeader("If-Modified-Since", "0")
    xmlHttpAlarmInfo.setRequestHeader("Cache-Control", "no-cache");
    xmlHttpAlarmInfo.send(null);
}

function ClearAlarmINfoSettings() {
    //RefreshAlarmInfoSettings();
    if (window.XMLHttpRequest) {// code for all new browsers
        xmlHttpClearAlarmInfo = new XMLHttpRequest();
    }
    else if (window.ActiveXObject) {// code for IE5 and IE6
        xmlHttpClearAlarmInfo = new ActiveXObject("Microsoft.XMLHTTP");
    }
    if (xmlHttpClearAlarmInfo == null) {
        return;
    }
    var url = "/cgi-bin/ClearAlarmInfo.cgi";
    xmlHttpClearAlarmInfo.onreadystatechange = stateClearAlarmInfo;
    xmlHttpClearAlarmInfo.open("GET", url, true);
    xmlHttpClearAlarmInfo.setRequestHeader("If-Modified-Since", "0")
    xmlHttpClearAlarmInfo.setRequestHeader("Cache-Control", "no-cache");
    xmlHttpClearAlarmInfo.send(null);
}

function stateChangedAlarmInfo() {
    var refresh_flag = 0;
    var i = 0;
    if (xmlHttpAlarmInfo.readyState == 4 || xmlHttpAlarmInfo.readyState == "complete") {
        if (xmlHttpAlarmInfo.status == 200) {
            xmlDoc = xmlHttpAlarmInfo.responseXML;
            xmlNode = xmlDoc.getElementsByTagName("AlarmInfoDetails")[0];
            //len+str every node
            for (i = 0; i < 12; i++) {
                //clear
                currentAlarmInfoLen = 0;
                currentAlarmInfoStr = "";
                currentAlarmInfoLen = xmlNode.getElementsByTagName("AlarmInfoLineLen")[i].textContent;
                if (currentAlarmInfoLen > 0) {
                    currentAlarmInfoStr = xmlNode.getElementsByTagName("AlarmInfoLineStr")[i].textContent;
                    if (currentAlarmInfoStr != ArrayAlarmInfoStr[i]) {
                        //clear
                        ArrayAlarmInfoStr[i] = "";
                        ArrayAlarmInfoLen[i] = 0;
                        refresh_flag = 1;
                        //set
                        ArrayAlarmInfoStr[i] = currentAlarmInfoStr;
                        ArrayAlarmInfoLen[i] = currentAlarmInfoLen;
                    }
                    else {
                        //not need refresh
                    }
                }
            }
            if (refresh_flag == 1) {
                refresh_flag = 0;
                document.getElementById("warninginfo").innerHTML = "";
                for (i = 0; i < 12; i++) {
                    if (ArrayAlarmInfoLen[i] > 0) {
                        AddWarningInfo(ArrayAlarmInfoStr[i]);
                    }
                }
            }
        }
        else {
        }
    }
}

function stateClearAlarmInfo() {
    if (xmlHttpClearAlarmInfo.readyState == 4 || xmlHttpClearAlarmInfo.readyState == "complete") {
        if (xmlHttpClearAlarmInfo.status == 200) {
            if (xmlHttpClearAlarmInfo.responseText == "OK") {
                document.getElementById("warninginfo").innerHTML = "";
                for (var i = 0; i < 12; i++) {
                    ArrayAlarmInfoStr[i] = "";
                }
            }
            else {

            }
        }
        else {
        }
    }
}

//check
function checkDecoderConfigure()
{
    var checkresult = 0;
    var output_value = document.getElementById("Resume_Time").value;
    if ((output_value < 10) || (output_value > 900)) {
        show_reveal_str("configure_set_label", "Error! Resume time must be between 10 and 900.", "#ff0000");
        
        checkresult = 1;
    }
    else {
       
    }
   
    return checkresult;
}

function Addressing_select_change() {
    var objs = document.getElementById("Addressing_config");
    var grade = objs.options[objs.selectedIndex].getAttribute('grade');
    switch (grade) {
        case "1":
            document.getElementById("Network1_IP").disabled = false;
            document.getElementById("Network1_Netmask").disabled = false;
            document.getElementById("Network1_Gateway").disabled = false;
            break;
        case "2":
            document.getElementById("Network1_IP").disabled = true;
            document.getElementById("Network1_Netmask").disabled = true;
            document.getElementById("Network1_Gateway").disabled = true;
            break;
        default: break;
    }
}

//date&time
function date_time_decoder()
{
    var date_value = document.getElementById("date_set_id").value;
    var time_value = document.getElementById("time_set_id").value;
    if (window.XMLHttpRequest) {// code for all new browsers
        xmlHttpChangeNTTDateTime = new XMLHttpRequest();
    }
    else if (window.ActiveXObject) {// code for IE5 and IE6
        xmlHttpChangeNTTDateTime = new ActiveXObject("Microsoft.XMLHTTP");
    }
    if (xmlHttpChangeNTTDateTime == null) {
        return;
    }
    var url = "/cgi-bin/ApplyNTTDateTime.cgi?Date=" + date_value + "&Time=" + time_value;
    xmlHttpChangeNTTDateTime.onreadystatechange = stateChangedNTTDateTime;
    xmlHttpChangeNTTDateTime.open("GET", url, true);
    xmlHttpChangeNTTDateTime.setRequestHeader("If-Modified-Since", "0")
    xmlHttpChangeNTTDateTime.setRequestHeader("Cache-Control", "no-cache");
    xmlHttpChangeNTTDateTime.send(null);
}

function stateChangedNTTDateTime() {
    if (xmlHttpChangeNTTDateTime.readyState == 4 || xmlHttpChangeNTTDateTime.readyState == "complete") {
        if (xmlHttpChangeNTTDateTime.status == 200) {
            if (xmlHttpChangeNTTDateTime.responseText == "OK") {
            }
            else {
            }
        }
        else {

        }
    }
}

function show_reveal_str_color(id, str, color) {
    document.getElementById(id).innerHTML = str;
    document.getElementById(id).style.color = color;
    document.getElementById(id).style.display = "inline";
}


//auto wait
function WaitAutoRefresh(str, id, str_label) {
    if (str != "Wait") {
        clearInterval(refreshWait);
        refreshWaitFlag = 0;
    }
    else {
        if (refreshWaitFlag == 0) {
            refreshWait = setInterval(function () { keep_wait_alive(id, str_label) }, 1000);
            refreshWaitFlag = 1;
        }
    }
}

function keep_wait_alive(id, str_label) {
    if (WaitCount == 0) {
        show_reveal_str_wait_alive(id, str_label + ".", "#ff6a00");
    }
    else if (WaitCount == 1) {
        show_reveal_str_wait_alive(id, str_label + "..", "#ff6a00");
    }
    else if (WaitCount == 2) {
        show_reveal_str_wait_alive(id, str_label + "...", "#ff6a00");
    }
    WaitCount++;
    WaitCount %= 3;
}

function show_reveal_str_wait_alive(id, str, color) {
    document.getElementById(id).innerHTML = str;
    document.getElementById(id).style.color = color;
    document.getElementById(id).style.display = "inline";
}

function formatSeconds(value) {
    var secondTime = parseInt(value);
    var minuteTime = 0;
    var hourTime = 0;
    var dayTime = 0;
    if (secondTime >= 60) {
        minuteTime = parseInt(secondTime / 60);
        secondTime = parseInt(secondTime % 60);
        if (minuteTime >= 60) {
            hourTime = parseInt(minuteTime / 60);
            minuteTime = parseInt(minuteTime % 60);
            if (hourTime >= 24) {
                dayTime = parseInt(hourTime / 24);
                hourTime = parseInt(hourTime % 24);
            }
        }
    }
    var result = "" + parseInt(secondTime) + "s";
    if (minuteTime > 0) {
        result = "" + parseInt(minuteTime) + "m" + result;
    }
    if (hourTime > 0) {
        result = "" + parseInt(hourTime) + "h" + result;
    }
    if (dayTime > 0) {
        result = "" + parseInt(dayTime) + "d" + result;
    }
    return result;
}
